package io.gitee.terralian.code.generator.service.preview.impl;

import java.io.File;
import java.io.FileWriter;
import java.util.StringJoiner;

import io.gitee.terralian.code.generator.controller.request.PreviewGenerateRequest;
import io.gitee.terralian.code.generator.service.preview.GenerateService;
import io.gitee.terralian.code.generator.service.preview.entity.PreviewData;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Service;

@Service
public class GenerateServiceImpl implements GenerateService {

    @Override
    public void generate(PreviewGenerateRequest request) {
        for (PreviewData previewData : request.getData()) {
            StringJoiner builder = new StringJoiner("/");
            builder.add(StrUtil.nullToEmpty(request.getBaseUrl()));
            builder.add(StrUtil.nullToEmpty(previewData.getCodeBaseUrl()));
            builder.add(StrUtil.nullToEmpty(previewData.getPackageUrl()));
            File templateParentPath = new File(builder.toString().replaceAll("//", "/"));
            FileUtil.mkdir(templateParentPath);

            builder.add(StrUtil.nullToEmpty(previewData.getFileName()));
            File targetFile = FileUtil.file(builder.toString().replaceAll("//", "/"));
            try (FileWriter fileWriter = new FileWriter(targetFile)) {
                fileWriter.write(previewData.getData());
                fileWriter.flush();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
